﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Framework;
using SchemaMonitor;
using System.Data;
using System.Text;

public partial class pages_TextMessage_Default : System.Web.UI.Page
{
    public string Contact { get { return CWeb.RequestStr("contact"); } }
    public string Number { get { return CWeb.RequestStr("number"); } }
    public int ImgId { get { return CWeb.RequestInt("imgId"); } }
    public int ImgIdx { get { return CWeb.RequestInt("imgIdx"); } }


    protected void Page_Init(object sender, EventArgs e)
    {
        if (ImgId > 0)
        {
            var key = string.Concat("ImgId", ImgId, "_", ImgIdx);
            byte[] img = (byte[])CSession.Get(key);
            if (null != img)
                Response.BinaryWrite(img);
            Response.End();
        }


        var d = CDataSrc.Default.MakeDictStrInt("SELECT ContactName, count(*)  FROM [TextMessage]  group by contactname  order by contactname");
        foreach (var i in d)
            CDropdown.Add(ddContact, CUtilities.NameAndCount( CUtilities.Truncate( i.Key), i.Value), i.Key);
        CDropdown.BlankItem(ddContact, "-- Any Contact --");
        CDropdown.SetValue(ddContact, Contact);

        if (!string.IsNullOrEmpty(Contact))
        {
            ddNumber.Visible = true;
            var sql = @"SELECT Addresses, count(*), ContactName
  FROM [vwTextMessages]
  group by ContactName, Addresses
  Having ContactName = @name
  order by ContactName, Addresses";
            var cmd = new CCommand(sql, new CNameValueList("name", Contact), false);
            d = CDataSrc.Default.MakeDictStrInt(cmd);
            foreach (var i in d)
                CDropdown.Add(ddNumber, CUtilities.NameAndCount(CUtilities.Truncate(i.Key), i.Value), i.Key);
            CDropdown.BlankItem(ddNumber, "-- Any Number --", "");
            CDropdown.SetValue(ddNumber, Number);
        }

    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Page_PreRender(object sender, EventArgs e)
    {
        var c = new CCriteriaList();

        if (Contact.Length > 0) c.Add("ContactName", Contact);
        if (Number.Length > 0) c.Add("Addresses", Number);

        var pi = ctrlPaging.Info;
        pi.TableName = "vwTextMessages";
        if (string.IsNullOrEmpty(pi.SortByColumn))
        {
            pi.SortByColumn = "[Date]";
            pi.Descending = false;
        }

        var where = new CSelectWhere("*", new CWhere("[vwTextMessages]", c, null), "[Date]");

        var ds = CDataSrc.Default.PagingWithFilters_Dataset(pi, c);

        dg.DataSource = ds;
        dg.DataBind();
    }

    protected void ddContact_SelectedIndexChanged(object sender, EventArgs e)
    {
        var c = ddContact.SelectedValue;
        Response.Redirect("default.aspx?contact=" + Server.UrlEncode(c), true);
    }

    protected void ddNumber_SelectedIndexChanged(object sender, EventArgs e)
    {
        var c = ddContact.SelectedValue;
        var n = ddNumber.SelectedValue;
        Response.Redirect("default.aspx?contact=" + Server.UrlEncode(c) + "&number=" + Server.UrlEncode(n), true);
    }

    protected void dg_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        var item = (DataGrid)sender;
        var i = e.Item;

        var c2 = i.Cells[1].Text;
        if (i.ItemType == ListItemType.Header)
        {
            i.CssClass = "th";
            return;
        }
        i.CssClass = c2.Contains("=> Me") ? "alt_row" : i.CssClass;

        var dr = (DataRowView)e.Item.DataItem;
        if (null == dr || null == dr.Row)
            return;

        var td = i.Cells[2];
        var len = CAdoData.GetInt(dr.Row, "ImagesLen");
        if (len > 0)
        {
            var id = CAdoData.GetInt(dr.Row, "Message");
            var obj = CSession.Get("Img_" + id);
            if (null == obj)
            {
                obj = CDataSrc.Default.ExecuteScalar(new CCommand("SELECT [Images] From TextMessage WHERE Message=@id", new CNameValueList("id", id), false));
                if (obj is byte[])
                    CSession.Set("Img_" + id, obj);
                else
                    CSession.Set("Img_" + id, new byte[] { });

            }

            byte[] b = (byte[])obj;
            var imgs = CProto.Deserialise<List<SchemaMonitor.xml.CImg>>(b);
            foreach (var x in imgs)
            {
                var idx = imgs.IndexOf(x);
                var key = string.Concat("ImgId", id, "_", idx);

                var img = new Image();
                td.Controls.Add(img);
                img.AlternateText = x.Name;
                img.ImageUrl = "default.aspx?imgId=" + id + "&imgIdx=" + imgs.IndexOf(x);
                img.Width = new Unit("300px");

                CSession.Set(key, x.Data);
            }
        }
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        var c = new CCriteriaList();

        if (Contact.Length > 0) c.Add("ContactName", Contact);
        if (Number.Length > 0) c.Add("Addresses", Number);


        var where = new CSelectWhere("*", new CWhere("[vwTextMessages]", c, null), "[Date]");

        var ds = CDataSrc.Default.SelectWhere_Dataset("[vwTextMessages]", c);
        CDataSrc.ExportToCsv(ds, Response);
        Response.End();
    }

    protected void btnFormat_Click(object sender, EventArgs e)
    {
        var c = new CCriteriaList();
        if (Contact.Length > 0) c.Add("ContactName", Contact);
        if (Number.Length  > 0) c.Add("Addresses",   Number);

        var msg = new CTextMessage();
        var mm = msg.SelectWhere(c);

        var ss = new List<string>();

        var sb = new StringBuilder();
        var lastFromTo = string.Empty;
        foreach (var i in mm)
        {
            if (ss.Contains(i.Body))
                continue;
            ss.Add(i.Body);

            if (lastFromTo != i.FromTo)
            {
                sb.AppendLine();
                sb.AppendLine("---------------------------------------");
                sb.Append("[").Append(i.FromTo).Append("] ");
                sb.Append(i.Date.ToString("[d MMM yyyy] [hh:mm:ss tt]"));
                sb.AppendLine();
            }
            sb.AppendLine("---------------------------------------");

            lastFromTo = i.FromTo;

            sb.AppendLine(i.Body.Replace("\r\n", "<br/>").Replace("\r", "<br>"));
        }
        sb.AppendLine("---------------------------------------");




        Response.ContentType = "text/plain";
        Response.Write(sb.ToString());
        Response.End();
    }
}